package sany.iec.service;

import lombok.extern.slf4j.Slf4j;
import org.openmuc.j60870.*;
import org.openmuc.j60870.ie.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author : 托马斯
 * @Date : 2025/6/26 17:42
 * @Description :
 */
@Service
@Slf4j
public class SendFunctionService {

    @Resource(name = "iec-connection")
    private Connection connection;

    /**
     * 进行遥控数据下发
     *
     * @param ioa  : 那个位置进行下发
     * @param flag : 值
     * @throws IOException
     */
    public void sendDataToSinglePointCommand(Integer ioa, boolean flag) throws IOException {
        InformationObject io = new InformationObject(
                ioa,
                new IeSinglePointWithQuality(flag, false, false, false, false)
        );

        ASdu command = new ASdu(
                ASduType.C_SC_NA_1,                   // 单点遥控命令
                false,                                // 非测试帧
                CauseOfTransmission.ACTIVATION,       // 激活
                false, false,
                0,                                     // originatorAddress
                1,                                     // commonAddress（视子站配置而定）
                new InformationObject[]{io}
        );

        connection.send(command);
        System.out.println("➡️ 已发送遥控命令 IOA=" + ioa + ", value=" + flag);
    }

    /**
     * @param ioa   : 那个位置进行下发
     * @param value : 值
     * @throws IOException
     */
    public void sendDataToSetPointCommand(Integer ioa, float value) throws IOException {
        InformationObject io = new InformationObject(ioa, new InformationElement[][]{
                {
                        new IeShortFloat((Float) (value)),  // M_ME_NC_1
                        // new IeScaledValue((short) (analogValues[i])), // M_ME_NB_1
                        new IeQuality(false, false, false, false, false)
                }
        });
        ASdu command = new ASdu(
                ASduType.C_SE_NC_1,                   // 单点遥调命令
                false,                                // 非测试帧
                CauseOfTransmission.ACTIVATION,       // 激活
                false, false,
                0,                                     // originatorAddress
                1,                                     // commonAddress（视子站配置而定）
                new InformationObject[]{io}
        );

        connection.send(command);
        System.out.println("➡️ 已发送遥控命令 IOA=" + ioa + ", value=" + value);
    }

}
